package com.adminx.service;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.adminx.dao.RoleDao;
import com.adminx.entity.Role;
import com.adminx.pojo.RolePojo;
import com.adminx.util.PageResults;

@Service
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class RoleService {
	
	@Autowired
	private RoleDao roleDao;
	
	/**
	 * 分页查询角色
	 * @param pageIndex 当前页
	 * @param pageSize 每页条数
	 * @return PageResults<Role>
	 */
	public PageResults<RolePojo> findAllRole(Integer pageIndex, Integer pageSize, String searchText){
		return this.roleDao.findAllRole(pageIndex, pageSize, searchText);
	}
	
	/**
	 * 通过角色ID获取角色
	 * @param roleID 角色ID
	 * @return 角色
	 */
	public RolePojo info(Long roleID){
		return this.roleDao.info(roleID);
	}
	
	/**
	 * 保存角色
	 * @param Role 角色
	 */
	public void save(Role role){
		//新增
		if(role.getRoleId() == null){
			this.roleDao.save(role);
		}
		//修改
		else{
			Role oldRole = this.roleDao.get(role.getRoleId());
			oldRole.setRoleName(role.getRoleName());
			oldRole.setRemark(role.getRemark());
			oldRole.setUpdateDate(new Date());
			oldRole.setCreateDate(role.getCreateDate());
			this.roleDao.update(oldRole);
		}
	}
	
	/**
	 * 删除角色
	 * @param roleID 角色ID
	 * @return 角色
	 */
	public int delBatch(String ids){
		return this.roleDao.delBatch(ids);
	}
	
	/**
	 * 向角色赋权限
	 * @param roleID 角色ID
	 * @param authoritys 权限集合
	 */
	public void grantAuthority(Long roleID,String authoritys){
		//移除该角色下原有权限
		this.roleDao.removeAuthority(roleID);
		//向角色赋权限
		this.roleDao.grantAuthority(roleID, authoritys);
	}
	
	/**
	 * 查询账户角色拥有情况
	 * @param accountId
	 * @return
	 */
	public List<RolePojo> findRoleListByAccount(Long accountId){
		 return this.roleDao.findRoleListByAccount(accountId);
	}

}
